import requests
import socket
import json

# 初始化参数
# 事先定义这几个参数不是必须的，只是为了提醒使用者需要获得哪些参数
USERNAME = '111'
PASSWORD = ''
OPERATOR = ''
IP = ''
BASEURL = 'http://10.9.1.3:801/eportal/' 

# 获取当前IP地址
def getHostName():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        IP = s.getsockname()[0]
        print('你的IP地址为:' + IP)
        return IP
    except Exception as e:
        print('获取IP失败！')
        print('错误内容：', e)
        print(e)
    finally:
        print('=====================================这是无聊的分隔符=======================================')
        s.close()

# 传入用户数据的目录
def getAdminConfig(adminFilePath):
    try:
        with open(adminFilePath, 'r', encoding = 'utf-8') as f:
            adminConfig = json.load(f)
            # return adminConfig
    except IOError as e:
        print('文件读取错误:', e)
    else:
        USERNAME = adminConfig['学号']
        PASSWORD = adminConfig['密码']
        OPERATOR = adminConfig['运营商']
        return USERNAME, PASSWORD, OPERATOR
        
# 发送GET登录请求
def login(USERNAME, PASSWORD, OPERATOR, IP):
    headers = {
        'Host': '10.9.1.3:801',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36',
        'Accept': '*/*',
        'Referer': 'http://10.9.1.3/',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
    }
    params = {
        'c': 'Portal',
        'a': 'login',
        'callback': 'dr1003',
        'login_method': '1',
        'user_account': ',0,' + USERNAME + '@' + OPERATOR,
        'user_password': PASSWORD,
        'wlan_user_ip': '10.70.91.132',
        'wlan_user_ipv6': '',
        'wlan_user_mac': '000000000000',
        'wlan_ac_ip': '',
        'wlan_ac_name': '',
        'jsVersion': '3.3.3',
        'v': '8425'
    }
    try:
        res = requests.get(BASEURL, headers = headers, params = params)
        return res.status_code
    except Exception as e:
        print('请求失败：', e)

# 主函数
def main():
    IP = getHostName()
    adminConfig = getAdminConfig('./admin.json')
    USERNAME, PASSWORD, OPERATOR = adminConfig
    resCode = login(USERNAME, PASSWORD, OPERATOR, IP)
    if resCode == 200:
        print('成功登录校园网！')
    else:
        print('登录校园网失败！')

if __name__ == '__main__':
    main()

